package cz.muni.fi.pa165.hauntedhouses.dao;

import cz.muni.fi.pa165.hauntedhouses.entity.House;
import cz.muni.fi.pa165.hauntedhouses.util.Util;
import java.util.Collections;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Jan Vyhnanek (374138)
 */
@Repository
public class HouseDAOImpl implements HouseDAO{
    
    @PersistenceContext(type=PersistenceContextType.EXTENDED)
    private EntityManager em;
    
    
    public void setEntityManager(EntityManager em){
        this.em = em;
    }

    @Override
    public void create(House house) {
        Util.validateHouse(house);
        if(house.getId() != null) {
            throw new IllegalArgumentException("This house is already created");
        }
        em.persist(house);
        em.flush();
        em.detach(house);
    }

    @Override
    public void update(House house) {
        Util.validateHouse(house);
        if(house.getId() == null) {
            throw new IllegalArgumentException("This house doesnt exist");
        }
        em.merge(house);
        em.flush();
        em.detach(house);
    }

    @Override
    public void remove(House house) {
        Util.validateHouse(house);
        if(house.getId() == null) {
            throw new IllegalArgumentException("This house doesnt exist");
        }
        House houseToRemove;
        houseToRemove = em.find(House.class, house.getId());
        em.remove(houseToRemove);
    }

    @Override
    public House get(Long id) {
        if(id == null) {
            throw new IllegalArgumentException("ID is NULL");
        }
        if(id < 0) {
            throw new IllegalArgumentException("ID < 0");
        }
        em.flush();
        House house = em.find(House.class, id);
        em.flush();
        em.detach(house);
        em.flush();
        return house;
    }

    @Override
    public List<House> findAll() {
        Query q = em.createQuery("from House"); 
        List<House> houses = q.getResultList();
        return Collections.unmodifiableList(houses);
    }

    @Override
    public List<House> findByName(String name) {
        if(name == null) {
            throw new IllegalArgumentException("Name is NULL");
        }
        
        Query q = em.createQuery("from House where name=:name");
        q.setParameter("name", name);
        List<House> houses = q.getResultList();
        return Collections.unmodifiableList(houses);
    }
    
}
